import {
  reqGetDoctors,
  reqGetHospitalDeparment,
  reqGetHospitalScheduleRule,
} from "@/api/hospital/hospitalList";
import {
  Departments,
  DoctorItems,
  HospitalScheduleItems,
} from "@/api/hospital/model/hospitalListTypes";
import { Button, Card, Col, message, Pagination, Row, Tag } from "antd";
import Table, { ColumnsType } from "antd/lib/table";
import Tree, { DataNode } from "antd/lib/tree";
import React, { Key, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function HospitalSchedule() {
  //准备树状结构的数据
  const treeData: DataNode[] = [
    {
      title: "parent 1",
      key: "0-0",
      children: [
        {
          title: "parent 1-0",
          key: "0-0-0",
          disabled: true,
          children: [
            {
              title: "leaf",
              key: "0-0-0-0",
              disableCheckbox: true,
            },
            {
              title: "leaf",
              key: "0-0-0-1",
            },
          ],
        },
        {
          title: "parent 1-1",
          key: "0-0-1",
          children: [
            {
              title: <span style={{ color: "#1890ff" }}>sss</span>,
              key: "0-0-1-0",
            },
          ],
        },
      ],
    },
  ];

  //表格数据
  let dataSource: any[] = [];

  let columns: ColumnsType<any> = [
    {
      title: "序号",
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "总预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "剩余预约数",
      dataIndex: "availableNumber",
    },
    {
      title: "挂号费(元)",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
      fixed: "right",
      width: 150,
    },
  ];

  //计算左侧树状结构的高度
  let height =
    document.documentElement.clientHeight - 64 - 34 - 24 * 2 - 22 - 14;

  //获取 url 中的 id 参数
  let { id } = useParams();
  let hoscode = id as string;

  //声明状态
  let [departments, setDepartments] = useState<Departments>([]);
  //展开节点的 depcode
  let [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  //声明与分页相关的状态
  let [current, setCurrent] = useState(1);
  let [total, setTotal] = useState(0);
  let [pageSize, setPageSize] = useState(5);
  //声明医院排班的状态
  let [hospitalSchedule, setHospitalSchedule] = useState<HospitalScheduleItems>(
    []
  );
  //声明医生列表的状态
  let [doctors, setDoctors] = useState<DoctorItems>([]);
  //设置医院名称的状态
  let [hosname, setHosname] = useState("");
  //设置科室名称的状态
  let [depname, setDepname] = useState("");
  //设置日期的状态
  let [workDate, setWorkDate] = useState("");
  //设置科室编号的状态
  let [depcode, setDepcode] = useState("");

  //声明
  let getDepartments = async () => {
    //获取所有的科室
    let departments = await reqGetHospitalDeparment(id as string);
    //使所有的一级科室全部禁用
    departments = departments.map((item) => {
      item.disabled = true;
      return item;
    });
    //获得所有一级科室的 key 也就是 depcode
    let depcodes = departments.map((item) => {
      return item.depcode;
    });
    //更新状态
    setExpandedKeys(depcodes);
    //更新科室的状态
    setDepartments(departments);

    //获得第一个一级科室的第一个子元素
    let depcode = (departments[0].children as Departments)[0].depcode;
    let depname = (departments[0].children as Departments)[0].depname;
    //更新状态 depcode 的状态
    setDepcode(depcode);
    setDepname(depname);
  };

  //获取排班规则
  let getHospitalSchedule = async () => {
    try {
      //发送请求获取第一个科室未来的排班
      let scheduleList = await reqGetHospitalScheduleRule({
        page: current,
        limit: pageSize,
        hoscode,
        depcode,
      });
      //设置状态
      setHospitalSchedule(scheduleList.bookingScheduleList);
      //设置总数的状态
      setTotal(scheduleList.total);
      //更新医院名称的状态
      setHosname(scheduleList.baseMap.hosname);

      //获取 workDate 的值
      let workDate = scheduleList.bookingScheduleList[0].workDate;
      //更新 workDate 的值
      setWorkDate(workDate);

      
    } catch (e) {
      //如果请求失败, 清空排班列表, 清空医生列表
      setHospitalSchedule([]);
      setDoctors([]);
      message.error("失败");
    }
  };

  //获取医生列表
  let getDoctors = async () => {
    //获取某天医生的排班信息
    let doctors = await reqGetDoctors({ hoscode, depcode, workDate });
    //更新医生列表的状态
    setDoctors(doctors);
  }

  //改变左侧科室的事件
  let changeDepartment = async (selectedKeys: Key[], info: any) => {
    //获取所点科室的编号和名称
    let depname = info.node.depname;
    let depcode = info.node.depcode;

    setDepname(depname);
    setDepcode(depcode);
  };

  //改变日期的事件
  let changeDate = (workDate: string) => {
    return async () => {
      setWorkDate(workDate);
    };
  };

  //声明 useEffect 组件挂载完毕钩子
  useEffect(() => {
    //获取所有的科室
    getDepartments();
  }, []);

  //声明 useEffect
  useEffect(() => {
    //判断
    if (!depcode) return;
    getHospitalSchedule();
  }, [depcode, depname, current, pageSize]);

  //
  useEffect(() => {
    //判断
    if(!workDate) return;
    getDoctors();
  }, [workDate]);

  //获得 navigate 函数
  let navigate = useNavigate();

  return (
    <Card>
      {/* 路径导航部分 */}
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>

      {/* 内容区域 */}
      <Row gutter={20}>
        <Col span={5}>
          <div
            style={{
              border: "solid 1px #aaa",
              height: height,
              overflowY: "scroll",
            }}
          >
            <Tree
              expandedKeys={expandedKeys}
              fieldNames={{
                title: "depname",
                key: "depcode",
              }}
              treeData={departments as []}
              selectedKeys={[depcode]}
              onSelect={changeDepartment}
            />
          </div>
        </Col>
        <Col span={19}>
          {/* 排班日期 */}
          <div>
            {hospitalSchedule.map((item) => {
              return (
                <Tag
                  color={workDate === item.workDate ? "green" : ""}
                  key={item.workDate}
                  style={{ cursor: "pointer" }}
                  onClick={changeDate(item.workDate)}
                >
                  <div>
                    {item.workDate} {item.dayOfWeek}
                  </div>
                  <div>
                    {item.availableNumber} / {item.reservedNumber}
                  </div>
                </Tag>
              );
            })}
          </div>
          <div className="h-20"></div>
          {/* 分页结构 */}
          <Pagination
            current={current}
            pageSize={pageSize}
            total={total}
            onChange={(page: number, pageSize: number) => {
              setCurrent(page);
              setPageSize(pageSize);
            }}
          />
          <div className="h-20"></div>
          {/* 表格部分 */}
          <Table
            pagination={false}
            columns={columns}
            dataSource={doctors}
            bordered
            rowKey={"id"}
          />

          <Button onClick={() => {
            navigate('/syt/hospital/hospitalList')
          }}>返回</Button>
        </Col>
      </Row>
    </Card>
  );
}
